package main.com.cyz.BinarySearch;

/**
 * @author fox
 * @version 1.0
 * @description
 * 乐扣35
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * 请必须使用时间复杂度为 O(log n) 的算法。
 *
 * 示例 1:
 *
 * 输入: nums = [1,3,5,6], target = 5
 * 输出: 2
 * 示例 2:
 *
 * 输入: nums = [1,3,5,6], target = 2
 * 输出: 1
 * 示例 3:
 *
 * 输入: nums = [1,3,5,6], target = 7
 * 输出: 4
 *
 * 提示:
 *
 * 1 <= nums.length <= 104
 * -104 <= nums[i] <= 104
 * nums 为 无重复元素 的 升序 排列数组
 * -104 <= target <= 104
 * @date 2024/5/17 8:34
 */

//考研二分查找返回值的应用
public class LeetCode35 {

    /**
     * @description 二分查找 - 标准版
     * @param nums
     * @param target
     * @return int
     * @author fox
     * @date 2024/5/17 8:37
    */
    public static int searchStandard(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;

        while (start <= end) {
            int mid = (start + end) >>> 1;
            if (target == nums[mid]) {
                return mid;
            } else if (target < nums[mid]) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return start;
    }

    /**
     * @param nums
     * @param target
     * @return int
     * @description 二分查找 - 改进版
     * @author fox
     * @date 2024/5/16 21:42
     */
    public static int searchImprove(int[] nums, int target) {
        int start = 0;
        int end = nums.length;

        while (start < end) {
            int mid = (start + end) >>> 1;
            if (target == nums[mid]) {
                return mid;
            } else if (target < nums[mid]) {
                end = mid;
            } else {
                start = mid + 1;
            }
        }
        return start;
    }

    /**
     * @param nums
     * @param target
     * @return int
     * @description 二分查找 - 平衡法
     * @author fox
     * @date 2024/5/16 21:45
     */
    public static int searchBalance(int[] nums, int target) {
        int start = 0;
        int end = nums.length;

        while (start + 1 < end) {
            int mid = (start + end) >>> 1;
            if (target < nums[mid]) {
                end = mid;
            } else {
                start = mid;
            }
        }
        return (nums[start] == target) ? start : end;
    }

    /**
     * @param nums
     * @param target
     * @return int
     * @description 二分查找 - 递归版
     * @author fox
     * @date 2024/5/16 21:45
     */
    public static int searchRecursion(int[] nums, int target) {
        return recursion(nums,target,0,nums.length-1);
    }

    private static int recursion(int[] nums,int target,int start,int end){
        if (start > end){
            return start;
        }
        int mid = (start + end) >>> 1;
        if (nums[mid] == target){
            return mid;
        }else if(target < nums[mid]){
            return recursion(nums,target,start,mid - 1);
        }else{
            return recursion(nums,target,mid + 1,end);
        }
    }

}
